<script setup lang="ts">
import { uploadAPI } from '@/apis/common';
import { createRentAPI, deleteEnterpriseAPI, deleteRentAPI, getEnterpriseListAPI, getRentBuildListAPI, getRentListAPI, outRentAPI } from '@/apis/enterprise';
import type { Datum, Enterprise, EnterpriseListParams, RentBuilding, RentParams } from '@/types/enterprise';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules, type UploadRawFile, type UploadRequestOptions } from 'element-plus';
import { ref, watch } from 'vue';

// 前端自定义类型
interface EnterpriseWithRent extends Enterprise{
  rentList:Datum[]//合同列表
}
// 企业列表
const params=ref<EnterpriseListParams>({
  page: 1,
    pageSize:2,
    name: ''
})
// 存储裂变
const list =ref<EnterpriseWithRent[]>([])
const total=ref(0)
// 调用接口获取列表
const getList= async()=>{
  const res=await getEnterpriseListAPI(params.value)
 list.value=res.data.rows.map(item=>({...item,rentList:[]}))
 total.value=res.data.total
}
getList()

// 搜索
const onSearch=()=>{
  params.value.page = 1
  // 刷新
  getList()
}

// 添加合同 - 表单数据
const rentForm = ref<RentParams>({
  buildingId: undefined, // 租赁楼宇id
  startTime: '', // 开始日期（不能小于今日日期）
  endTime: '', // 租赁结束日期
  contractUrl: '', // 合同附件url
  contractId: 0, // 合同附件id
  type: 0, // 操作类型，添加合同0，续签合同1
  enterpriseId: 0 // 企业id
})

// 获取楼宇列表
const buildList = ref<RentBuilding[]>([]) 

// 添加合同
const visible=ref(false)
// 打开弹窗
const addRent=async(id:number)=>{

    // 保存企业id
    rentForm.value.enterpriseId=id
  visible.value=true

  const res=await getRentBuildListAPI()
  buildList.value=res.data

  
}
const fileList=ref<UploadRawFile[]>([])
// 添加合同-确定
const addRentConfirm=async()=>{{
  try{
      await createRentAPI(rentForm.value)
    ElMessage.success('添加合同成功')
    getList()
    closeRent()
    // 清空表单
    addFormRef.value?.resetFields()
    // 清空数组表单
    timeArr.value=[]
    // 清空文件列表
    fileList.value=[]
     rentForm.value =({
  buildingId: undefined, // 租赁楼宇id
  startTime: '', // 开始日期（不能小于今日日期）
  endTime: '', // 租赁结束日期
  contractUrl: '', // 合同附件url
  contractId: 0, // 合同附件id
  type: 0, // 操作类型，添加合同0，续签合同1
  enterpriseId: 0 // 企业id
})

  }catch{
    ElMessage.error('添加合同失败')
  }
 
  
}} 

// 添加合同-关闭弹窗
const closeRent = () => {
  visible.value = false
}

  //上传成功校验表单
  const  addFormRef=ref<FormInstance>()
// 添加合同数据

// 添加合同 - 表单校验
const rentRules = ref<FormRules<RentParams>>({
  buildingId: [
    { required: true, message: '请选择楼宇', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择租赁日期', trigger: 'blur' }
  ],
  contractId: [
    { required: true, message: '请上传合同文件' }
  ]
})
 // 时间选择器 - 监听时间变化
 const timeArr = ref<string[]>([])
    watch(timeArr, (val) => {
      if (val) {
        rentForm.value.startTime = val[0]
        rentForm.value.endTime = val[1]
      } else {
        rentForm.value.startTime = ''
        rentForm.value.endTime = ''
      }
    }, { deep: true })
  // 通过 disabledDate 函数，来设置禁用掉的日期。
  const disabledDate = (time: Date) => {
    // 不能小于今日日期，包含今天 （ 1000 * 60 * 60 * 24 -> 1天的毫秒数 ）
    return time.getTime() < Date.now() - 1000 * 60 * 60 * 24
  }

// 上传合同
const   onUploadRequest=async(options: UploadRequestOptions)=>{
    const  fd=new  FormData()
    fd.append('file',options.file)
    fd.append('type' ,'contract')
    // 调用接口上传
   const res=uploadAPI(fd)
  // 将合同数据添加到表单
     rentForm.value.contractUrl=(await res).data.url
     rentForm.value.contractId=(await res).data.id
    addFormRef.value?.validateField('contractId')
}
// 添加后清空
const  removeContract=()=>{
  rentForm.value.contractUrl = ''
  rentForm.value.contractId = undefined
  // 校验
  addFormRef.value?.validateField('contractId')
}
// 校验文件大小
const beforeUpload=(rawFile: UploadRawFile)=>{   
  const allowSize =  5 * 1024 * 1024
    if(rawFile.size > allowSize){
   ElMessage.error('文件大小不能超过5M')
   return false
    }
    return true
}

// 企业合同展开行
const expandChange= async(row:EnterpriseWithRent)=>{
  const  res= await getRentListAPI(row.id) 
row.rentList=res.data
}

// 退租
const outRent=async(row:Datum)=>{
  ElMessageBox.confirm('退租不可撤回，是否确认退租当前楼宇?', '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      // 发送请求，更新后端合同状态
      await outRentAPI(row.id)
      // 更新前端合同状态，退租按钮变禁用
      row.status = 3
      // 轻提示
      ElMessage.success('退租成功')
    }).catch(() => {
      // 点击取消，什么也不做
    })
}

// 删除合同
const deleteRent = async (rentRow: Datum, row: EnterpriseWithRent) => {
  try {
    await ElMessageBox.confirm('是否确认删除当前合同?', '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 发送请求，更新后端合同状态
    await deleteRentAPI(rentRow.id)
    
    // 确保 rentList 存在
    if (row.rentList) {
      // 删除过滤掉合同（前端）
      row.rentList = row.rentList.filter(item => item.id !== rentRow.id)
    }
    
    ElMessage.success('删除成功')
    // 删除刷新
    getList()
  } catch  {
    // 用户点击取消或发生错误时不做处理
  }
}

// 删除企业
const deleteEnterprise=async(id:number)=>{
// 判断是否有租赁合同
const res=await getRentListAPI(id)
if(res.data.some(item=>item.status!==3)){
  ElMessage.error('当前企业有租赁合同，不能删除')
  return
}

ElMessageBox.confirm('是否确认删除当前企业?', '温馨提示', {
  confirmButtonText: '确定',
  cancelButtonText: '取消',
  type: 'warning'
}).then(async () => {
  await deleteEnterpriseAPI(id)
  // 提示框
  ElMessage.success('删除成功')
  // 删除刷新
  getList()
})
}

</script>


<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input clearable placeholder="请输入内容"  class="search-main" 
         v-model="params.name"
         @clear="onSearch"

      />
      <el-button type="primary" @click="onSearch" >查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/addenterprise')">添加企业</el-button>
    </div>
    <!-- 下拉表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="list"  @expand-change="expandChange" row-key="id" >
        <el-table-column type="expand" width="55">
          <template #default="{row}">
      <el-table :data="row.rentList">
        <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
        <el-table-column label="租赁起始时间" prop="startTime" />
        <el-table-column label="合同状态">
          <template v-slot="{ row }">
         <el-tag v-if="row.status === 0" type="warning">待生效</el-tag>
         <el-tag v-else-if="row.status === 1" type="success">生效中</el-tag>
         <el-tag v-else-if="row.status === 2" type="info">已到期</el-tag>
         <el-tag v-else-if="row.status === 3" type="danger">已退租</el-tag>
         </template>
        </el-table-column>

        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" type="text" :disabled="row.status===3" @click="outRent(row)">退租</el-button>
            <el-button size="small" type="text" :disabled="row.status!==3" @click="deleteRent(row, row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="120" />
        <el-table-column label="企业名称" width="320"  prop="name"/>
        <el-table-column label="联系人"  prop="contact"/>
        <el-table-column label="联系电话"  prop="contactNumber"/>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button size="small" type="text"  @click="addRent(row.id)">添加合同</el-button>
            <el-button size="small" type="text">查看</el-button>
            <el-button size="small" type="text" @click="$router.push(`/addenterprise/${row.id}`)">编辑</el-button>
            <el-button size="small" type="text" @click="deleteEnterprise(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination  :total="total"   
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[2, 5, 10, 20, 100]"
      v-model:page-size="params.pageSize"
      v-model:current-page="params.page"
      @change="getList()" />
    </div>
    <el-dialog title="title" width="600px" v-model="visible" >
      <!-- 表单模版 -->
<div class="form-container">
  <el-form ref="addFormRef" :model="rentForm" :rules="rentRules" label-position="top">
    <el-form-item label="租赁楼宇" prop="buildingId">
      <el-select v-model="rentForm.buildingId" placeholder="请选择">
        <el-option v-for="item in buildList" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
    </el-form-item>
    <el-form-item label="租赁起止日期" prop="endTime">
      <el-date-picker v-model="timeArr" type="daterange" range-separator="至" start-placeholder="开始日期"
        end-placeholder="结束日期" value-format="YYYY-MM-DD" :disabled-date="disabledDate" />
    </el-form-item>
    <el-form-item label="租赁合同" prop="contractId">
      <el-upload accept=".doc, .pdf"
      v-model:file-list="fileList"
      :http-request="onUploadRequest"
      @remove="removeContract"
      :before-upload="beforeUpload">
        <el-button size="small" type="primary" plain>上传合同文件</el-button>
        <template #tip>
          <div class="el-upload__tip">支持扩展名：.doc .pdf, 文件大小不超过5M</div>
        </template>
      </el-upload>
    </el-form-item>
  </el-form>
</div>  
{{ rentForm }}
<template #footer>
        <el-button @click="closeRent">取消</el-button>
        <el-button type="primary" @click="addRentConfirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>


<style lang="scss" scoped>
.building-container {
  padding: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>